import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Container,
  Paper,
  Button,
  Typography,
  Box,
  Alert,
} from '@mui/material';
import MovieForm from './MovieForm';
import MovieList from './MovieList/MovieList';
import MovieOrderList from './MovieOrderList/MovieOrderList';
import { apiRequest, API_PATHS } from '../config/api';

const MovieManagement: React.FC = () => {
  const navigate = useNavigate();
  const [movieData, setMovieData] = useState({
    title: '',
    description: '',
    totalTickets: '',
    price: '',
    showtime: null as Date | null,
  });
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [movies, setMovies] = useState<any[]>([]);
  const [editMovie, setEditMovie] = useState<any>(null);
  const [openDialog, setOpenDialog] = useState(false);
  const [orderDialogOpen, setOrderDialogOpen] = useState(false);
  const [selectedMovie, setSelectedMovie] = useState<any>(null);
  const [movieOrders, setMovieOrders] = useState<any[]>([]);
  const [formDialogOpen, setFormDialogOpen] = useState(false);

  const handleViewOrders = async (movie: any) => {
    try {
      const data = await apiRequest(API_PATHS.MOVIE_ORDERS(movie._id));
      setSelectedMovie(movie);
      setMovieOrders(data);
      setOrderDialogOpen(true);
    } catch (error) {
      setError('获取订单列表失败');
    }
  };

  useEffect(() => {
    const userStr = localStorage.getItem('user');
    if (!userStr) {
      navigate('/');
      return;
    }

    const user = JSON.parse(userStr);
    if (user.role !== 'admin') {
      navigate('/');
      return;
    }
  }, [navigate]);

  // 获取电影列表
  const fetchMovies = async () => {
    try {
      const data = await apiRequest(API_PATHS.MOVIES);
      setMovies(data);
    } catch (error) {
      setError('获取电影列表失败');
    }
  };

  useEffect(() => {
    fetchMovies();
  }, []);

  const handleEdit = (movie: any) => {
    setEditMovie(movie);
    setMovieData({
      title: movie.title,
      description: movie.description,
      totalTickets: movie.totalTickets.toString(),
      price: movie.price.toString(),
      showtime: new Date(movie.showtime),
    });
    setFormDialogOpen(true);
  };

  const handleDelete = async (movieId: string) => {
    if (!window.confirm('确定要删除这部电影吗？')) {
      return;
    }

    try {
      await apiRequest(API_PATHS.MOVIE_DETAIL(movieId), {
        method: 'DELETE'
      });
      setSuccess('电影删除成功！');
      fetchMovies();
    } catch (error: any) {
      setError(error?.message || '删除电影失败，请稍后重试');
      console.error('删除电影时发生错误:', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    try {
      const path = editMovie ? API_PATHS.MOVIE_DETAIL(editMovie._id) : API_PATHS.MOVIES;
      const method = editMovie ? 'PUT' : 'POST';

      await apiRequest(path, {
        method,
        body: JSON.stringify({
          title: movieData.title,
          description: movieData.description,
          totalTickets: parseInt(movieData.totalTickets),
          price: parseFloat(movieData.price),
          showtime: movieData.showtime,
        }),
      });

      setSuccess(editMovie ? '电影修改成功！' : '电影上架成功！');
      setFormDialogOpen(false);
      setEditMovie(null);
      setMovieData({
        title: '',
        description: '',
        totalTickets: '',
        price: '',
        showtime: null,
      });
      fetchMovies();
    } catch (error) {
      setError('服务器连接失败');
    }
  };

  const handleAddMovie = () => {
    setEditMovie(null);
    setMovieData({
      title: '',
      description: '',
      totalTickets: '',
      price: '',
      showtime: null,
    });
    setFormDialogOpen(true);
  };

  return (
    <Container component="main" maxWidth="lg" sx={{
      minHeight: '100vh',
      position: 'relative',
      '&::before': {
        content: "''",
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'linear-gradient(135deg, #0a192f 0%, #203a43 100%)',
        zIndex: -2,
      },
      '&::after': {
        content: "''",
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
        backgroundRepeat: 'repeat',
        opacity: 0.3,
        zIndex: -1,
      }
    }}>
      <Paper elevation={3} sx={{
        mt: 8,
        p: 4,
        background: 'rgba(255, 255, 255, 0.05)',
        backdropFilter: 'blur(10px)',
        borderRadius: '16px',
        border: '1px solid rgba(255, 255, 255, 0.1)'
      }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
          <Typography component="h1" variant="h5" sx={{
            color: 'white',
            fontWeight: 'bold',
            textShadow: '2px 2px 4px rgba(0,0,0,0.3)'
          }}>
            电影管理
          </Typography>
          <Button
            variant="contained"
            onClick={handleAddMovie}
            sx={{
              background: 'linear-gradient(45deg, #1976d2 30%, #64b5f6 90%)',
              color: 'white',
              fontWeight: 'bold',
              '&:hover': {
                background: 'linear-gradient(45deg, #64b5f6 30%, #1976d2 90%)',
              },
            }}
          >
            添加电影
          </Button>
        </Box>

        {error && (
          <Alert severity="error" sx={{ mb: 2, bgcolor: 'rgba(211, 47, 47, 0.1)' }}>
            {error}
          </Alert>
        )}

        {success && (
          <Alert severity="success" sx={{ mb: 2, bgcolor: 'rgba(46, 125, 50, 0.1)' }}>
            {success}
          </Alert>
        )}

        <MovieList
          movies={movies}
          onEdit={handleEdit}
          onDelete={handleDelete}
          onViewOrders={handleViewOrders}
        />

        <MovieForm
          open={formDialogOpen}
          onClose={() => setFormDialogOpen(false)}
          onSubmit={handleSubmit}
          movieData={movieData}
          setMovieData={setMovieData}
          isEdit={!!editMovie}
        />

        <MovieOrderList
          open={orderDialogOpen}
          onClose={() => setOrderDialogOpen(false)}
          movieTitle={selectedMovie?.title || ''}
          orders={movieOrders}
        />
      </Paper>
    </Container>
  );
};

export default MovieManagement;